
package com.platform.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 作者: @author  <br>
 * 时间: 2020-04-10 13:26<br>
 * 描述: Base64 <br>
 */
@Slf4j
public class AESUtil {

    /**
     * key为16位
     */
    private static String KEY = "_aes_secret_key_";

    private static String IV = "_aes_secret_iv__";


    /**
     * 加密方法
     *
     * @param data 要加密的数据
     * @param key  加密key
     * @param iv   加密iv
     * @return 加密的结果
     * @throws Exception
     */
    public static String encrypt(String data, String key, String iv) throws Exception {
        try {
            //"算法/模式/补码方式"NoPadding PkcsPadding
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密方法
     *
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv   解密iv
     * @return 解密的结果
     * @throws Exception
     */
    public static String desEncrypt(String data, String key, String iv) throws Exception {
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 使用默认的key和iv加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) throws Exception {
        return encrypt(data, KEY, IV);
    }

    /**
     * 使用默认的key和iv解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String data) throws Exception {
        return desEncrypt(data, KEY, IV);
    }

    /**
     * 联联周边 aes加密
     *
     * @param data      对象转为json字符串
     * @param secretKey AES秘钥
     * @return 加密后的字符串
     */
    public static String aesEncrypt(String data, String secretKey) {
        try {
            // 加密算法/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] dataBytes = data.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64Utils.decodeFromString(secretKey), "AES"));
            byte[] result = cipher.doFinal(dataBytes);
            return Base64Utils.encodeToString(result);
        } catch (Exception e) {
            log.error("执行CodecUtil.aesEncrypt失败：data={}，异常：{}", data, e);
            return null;
        }

    }

    /**
     * 联联周边 解密
     * @param encryptedDataBase64 加密后的字符串
     * @param securityKey         AES秘钥
     * @return 解密后的json字符串
     */
    public static String aesDecrypt(String encryptedDataBase64, String securityKey) {
        try {
            // 加密算法/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] dataBytes = Base64Utils.decodeFromString(encryptedDataBase64);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64Utils.decodeFromString(securityKey), "AES"));
            byte[] result = cipher.doFinal(dataBytes);
            return new String(result,StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("执行aesDecrypt失败：data={}，异常：{}", encryptedDataBase64, e);
        }
        return null;
    }

//    public static Map<String,Object> getData(Map<String,Object> map){
//        Long timeMillis = System.currentTimeMillis();
//        String sign = Md5Utils.encrypt(AESUtil.aesEncrypt(JSON.toJSONString(map),AesUtils.SECRETKEY) + AesUtils.CHANNELID + timeMillis);
//        Map<String ,Object> params = new HashMap<>();
//        params.put("timestamp",timeMillis);
//        params.put("sign",sign);
//        params.put("channelId",AesUtils.CHANNELID);
//        params.put("encryptedData",AesUtils.aesEncrypt( JSON.toJSONString(map),AesUtils.SECRETKEY));//加密后的数据
//        return params;
//    }

}
